import warehouseService from "@/api/services/wms/warehouseService";
import { TableToolbar } from "@/components/grid/TableToolbar";
import MultiUserSelector from "@/pages/components/selector/MultiUserSelect";
import { Button } from "antd";
import Table, { type ColumnsType } from "antd/es/table";
import { forwardRef, useEffect, useImperativeHandle, useMemo, useState } from "react";
import { toast } from "sonner";
import type { UserInfo } from "#/entity";

interface WarehouseUserProps {
	warehouseId: React.Key;
}

export interface WarehouseUserHandles {
	getNewUserIds: () => React.Key[];
	getDeleteUserIds: () => React.Key[];
}

const WarehouseUserPage = forwardRef<WarehouseUserHandles, WarehouseUserProps>(({ warehouseId }, ref) => {
	const [loading, setLoading] = useState(false);
	const [list, setList] = useState<UserInfo[]>([]);
	const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
	const [addUserIds, setAddUserIds] = useState<React.Key[]>([]);
	const [deleteIds, setDeleteIds] = useState<React.Key[]>([]);
	const [tableSize, setTableSize] = useState<"large" | "middle" | "small">("middle");

	const [selectVisiable, setSelectVisiable] = useState(false);

	useImperativeHandle(
		ref,
		() => ({
			getNewUserIds: () => addUserIds,
			getDeleteUserIds: () => deleteIds,
		}),
		[addUserIds, deleteIds],
	);

	//动态设置表格高度
	const [tableScrollY, setTableScrollY] = useState(0);
	const PAGE_OFFSET_HEIGHT = 403;
	const updateTableHeight = () => {
		const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
		setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		updateTableHeight(); // 初始化
		window.addEventListener("resize", updateTableHeight);
		return () => window.removeEventListener("resize", updateTableHeight);
	}, []);

	const columns: ColumnsType<UserInfo> = [
		{ key: "account", title: "账号", dataIndex: "account" },
		{ key: "name", title: "姓名", dataIndex: "name" },
		{ key: "phone", title: "手机号", dataIndex: "phone" },
	];

	const [selectedValues, setSelectedValues] = useState<string[]>(() =>
		columns.filter((col) => col.key !== "operation").map((col) => String(col.key!)),
	);

	const filteredColumns = useMemo(() => {
		return [...columns.filter((col) => selectedValues.includes(String(col.key)) || col.key === "operation")].sort(
			(a, b) => {
				const originalIndex = columns.findIndex((c) => c.key === a.key);
				const targetIndex = columns.findIndex((c) => c.key === b.key);
				return originalIndex - targetIndex;
			},
		);
	}, [selectedValues]);

	//加载表格数据
	const fetchPageList = () => {
		setLoading(true);
		warehouseService
			.warehouseUsers(warehouseId)
			.then((res) => {
				setList(res);
			})
			.catch((error) => {
				console.log(error);
				toast.error("获取数据失败！", error);
			})
			.finally(() => {
				setLoading(false);
			});
	};

	// biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
	useEffect(() => {
		fetchPageList();
	}, [warehouseId]);

	const handleAdd = () => {
		setSelectVisiable(true);
	};

	const handleDelete = () => {
		setList((prevList) => {
			// 计算要删除的ID（基于当前最新状态）
			const newDeleteIds = [...deleteIds];
			const newAddUserIds = [...addUserIds];
			
			const newList = prevList.filter((user) => {
				if (selectedRowKeys.includes(user.id)) {
					// 如果ID在addUserIds中，从addUserIds中移除
					if (newAddUserIds.includes(user.id)) {
						const index = newAddUserIds.indexOf(user.id);
						if (index > -1) {
							newAddUserIds.splice(index, 1);
						}
					} 
					// 如果ID不在deleteIds中且不在addUserIds中，添加到deleteIds
					else if (!deleteIds.includes(user.id)) {
						newDeleteIds.push(user.id);
					}
					return false;
				}
				return true;
			});

			// 同步更新 deleteIds 和 addUserIds
			setDeleteIds(newDeleteIds);
			setAddUserIds(newAddUserIds);

			return newList;
		});

		setSelectedRowKeys([]);
	};

	const handleSelect = (selectedUsers: UserInfo[]) => {
		setList((prevList) => [...prevList, ...selectedUsers]);

		setAddUserIds((prevIds) => {
			const newIds = new Set([...prevIds, ...selectedUsers.map((u) => u.id)]);
			return Array.from(newIds);
		});

		setSelectVisiable(false);
	};

	return (
		<>
			<div className="flex justify-between mb-4">
				<div className="flex gap-2">
					<Button type="primary" onClick={handleAdd}>
						新增
					</Button>
					<Button danger disabled={selectedRowKeys.length === 0} onClick={handleDelete}>
						删除
					</Button>
				</div>
				<TableToolbar
					onRefresh={() => fetchPageList()}
					onSizeChange={setTableSize}
					columns={columns}
					selectedValues={selectedValues}
					onColumnChange={setSelectedValues}
				/>
			</div>
			<Table
				rowKey="id"
				size={tableSize}
				scroll={{ x: "max-content", y: tableScrollY }}
				loading={loading}
				pagination={false}
				columns={filteredColumns}
				dataSource={list}
				rowSelection={{
					type: "checkbox",
					selectedRowKeys: selectedRowKeys,
					onChange: (selectedKeys) => {
						setSelectedRowKeys(selectedKeys as React.Key[]);
					},
				}}
			/>

			<MultiUserSelector
				open={selectVisiable}
				relateTableName="wms_warehouse_user"
				bizId={warehouseId}
				relateFiled="warehouse_id"
				onCancel={() => setSelectVisiable(false)}
				onOk={(selectUsers) => handleSelect(selectUsers)}
			/>
		</>
	);
});

export default WarehouseUserPage;
